﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using Citi.Import.Util;
using Citi.ResourceConsolidation.Domain;
using Citi.RoutineBase;

namespace Citi.ResourceConsolidation.SchedulerUI.GDW
{
    public class GDWUpdateDatabase : IExecutableRoutine
    {
        public IEnumerable<RoutineParameter> Parameters { get { return null; } }
        private readonly string InputGDWFolder = @"\\gruvnascti0016.wlb.lac.nsroot.net\DATA_GRP1\FTOOLS\Apps\GDWAutomation\ExtractedFile\";

        public void Rollback(ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {

        }

        public void Start(DateTime scheduledDate, ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {
            currentAction.Description = string.Format("Looking for GDW Files in {0}", InputGDWFolder);
            var fileName = Directory.GetFiles(InputGDWFolder).OrderByDescending(x => File.GetLastWriteTime(x)).First();

            if (fileName != null && fileName.Any())
            {
                currentAction.Description = "Moving old data to history table";
                new ResourceMonth().MoveResourceMonthToHistory();
                currentAction.Description = string.Format("The file {0} was found", Path.GetFileName(fileName));
                UpdateGDW(fileName, ref currentAction);
                //MoveFile(fileName, currentAction);
            }
        }

        public void Stop(ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {

        }

        public DateTime GetLastBusinessDay(int Year, int Month)
        {
            DateTime LastOfMonth = default(DateTime);
            DateTime LastBusinessDay = default(DateTime);
            LastOfMonth = new DateTime(Year, Month, DateTime.DaysInMonth(Year, Month));

            if (LastOfMonth.AddDays(-8).DayOfWeek == DayOfWeek.Sunday)
                LastBusinessDay = LastOfMonth.AddDays(-2);
            else if (LastOfMonth.DayOfWeek == DayOfWeek.Saturday)
                LastBusinessDay = LastOfMonth.AddDays(-1);
            else
                LastBusinessDay = LastOfMonth.AddDays(-8);

            return LastBusinessDay;
        }

        private void MoveFile(string fileName, ICurrentAction currentAction)
        {
            currentAction.Description = "Moving file to BKP folder";
            var targetPath = Path.Combine(InputGDWFolder, "bkp", fileName);

            File.Copy(fileName, targetPath, true);
            File.Delete(fileName);
        }

        private void UpdateGDW(string path, ref ICurrentAction currentAction)
        {
            Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture("en-US");

            List<Error> errors = null;
            currentAction.Description = "Reading GDW File";

            var dataTable = Conversion.ReadExcel(path, ref errors, null, 2);
            var referenceDate = DateTime.ParseExact(System.IO.Path.GetFileName(path.ToString()).Substring(4, 8), "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None);

            currentAction.Description = "Dropping previous data";
            new ResourceMonth().DeletePreviousData(referenceDate);

            List<Resource> resources;

            errors = ResourceUpdateDatabase.ImportResourceConsolidation(referenceDate, currentAction, errors, dataTable, ResourceType.GDW, out resources);

            currentAction.Description = "Checking imported data";

            var data = new Domain.ResourceMonth().SelectAll<ResourceMonth>().Count(x => x.ReferenceDate == DateTime.Today);

            if (data == 0)
                throw new Exception("No data was found on database");

            currentAction.Description = "Data is ok";
        }
    }
}
